<!--
 * @Author: zj
 * @LastEditors: JESS
 * @Date: 2022-06-14 15:41:42
 * @LastEditTime: 2022-08-03 14:04:03
-->
<template>
	<div class="congestion-content " style="z-index: 3">
		<!-- <div class="title">定期分析统计</div> -->
		<div class="tag-group">
			<div class="date">
				<el-date-picker style="width: 100%" v-model="time" type="daterange" range-separator="至"
					value-format="YYYY-MM-DD" format="YYYY-MM-DD" start-placeholder="选择开始日期" end-placeholder="选择结束日期" />
			</div>
		</div>
		<!-- <div class="tag-group">
      <div class="date">
        <el-select style="width: 100%" v-model="searchForm.pageNum" placeholder="请选择分析数量">
          <el-option v-for="(item, index) in list" :key="index" :label="item" :value="item" />
        </el-select>
      </div>
    </div> -->
		<div>
			<el-button type="primary" @click="searchData">查询</el-button>
			<el-button plain @click="resetForm">重置</el-button>
		</div>

		<!-- <div class="pop-mock" v-if="cellCtn">{{cellCtn}}</div> -->

		<el-table :data="tableData" style="width: 100%" v-loading="tableLoad"
			element-loading-background="rgba(0, 0, 0, 0.8)" @cell-mouse-enter="mouseEnter" @cell-click="clickItemTr">
			<el-table-column label="排行" width="100">
				<template #default="{ $index }">
					<div class="index-color">{{ $index + 1 }}</div>
				</template>
			</el-table-column>
			<el-table-column prop="roadname" label="拥堵路段">
				<template #default="scope">
					<el-popover effect="light" trigger="hover" placement="top" width="auto">
						<template #default>
							<div>{{ scope.row.roadsegId }}</div>
							<div> {{ scope.row.semantic }}</div>
						</template>
						<template #reference>
							{{ scope.row.roadname }}
						</template>
					</el-popover>
				</template>
			</el-table-column>
			<el-table-column label="拥堵指数" width="100">
				<template #default="{ row }">
					<span class="congestion-num" :class="{
              red: row.congestIndex > 2,
              orange: row.congestIndex > 1.5 && row.congestIndex < 2,
            }">{{ Number(row.congestIndex).toFixed(2) }}</span>
				</template>
			</el-table-column>
		</el-table>
	</div>
</template>

<script>
	import {
		defineComponent,
		toRefs,
		reactive,
		onMounted,
		ref,
		computed
	} from 'vue';
	import customDatePicker from '@/components/customDatePicker';
	import {
		formatToDateTime
	} from '@/utils/dateUtil';
	import {
		QueryRoadsegRank
	} from '@/api/ctdd';
	import {
		useMapStore
	} from '@/store/modules/map';
	import {
		getCoordinateBySplitName
	} from '@/api/tomae';

	export default defineComponent({
		components: {
			customDatePicker
		},
		setup() {
			const mapStore = useMapStore();
			const state = reactive({
				map: computed(() => mapStore.ownMap),
				// 6/25
				tableData: [],
				polylineList: [],
				searchForm: {
					startDate: '',
					endDate: '',
					pageNum: '',
				},
				time: [],
				list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
				tableLoad: false,
				cellCtn: '',
			});

			// 获取当前时间
			const getToday = (add) => {
				var date = new Date();
				if (add) {
					date = new Date(date.getTime() + 1000 * 60 * 60 * 24 * add);
				}
				var year = date.getFullYear();
				var dateArr = [
					date.getMonth() + 1,
					date.getDate(),
					date.getHours(),
					date.getMinutes(),
					date.getSeconds(),
				];
				for (var i = 0; i < dateArr.length; i++) {
					if (dateArr[i] >= 1 && dateArr[i] <= 9) {
						dateArr[i] = '0' + dateArr[i];
					}
				}
				var strDate = year + '-' + dateArr[0] + '-' + dateArr[1];
				return strDate;
			};
			const mouseEnter = (row, column, cell, event) => {
				// console.log("row",row);
				state.cellCtn = '';
				state.cellCtn = `${row.roadsegId} - ${row.semantic}`;
			};
			const searchData = () => {
				if (state.time.length) {
					state.searchForm.startDate = state.time[0];
					state.searchForm.endDate = state.time[1];
				}
				getData();
			};
			const getData = () => {
				state.tableLoad = true;
				QueryRoadsegRank(state.searchForm).then((res) => {
					state.tableData = res;
					state.tableLoad = false;
				});
			};
			const resetForm = () => {
				state.time = [getToday(-1), getToday()];
				state.searchForm.pageNum = '';
				searchData();
			};
			//单行点击
			const clickItemTr = async (row) => {
				state.currentRow = row;
				const data = await getCoordinateBySplitName({
					roadName: row.roadname
				});
				if (data.lng && data.lat) {
					const conPoint = new window.BMap.Point(data.lng, data.lat);
					state.map.centerAndZoom(conPoint, 16);
				}

				let firstPoint = ''
				let lastPoint = ''
				firstPoint = row.origin.split(',')
				lastPoint = row.terminus.split(',')
				state.map.clearOverlays();
				state.startPoint = '';
				state.endPoint = '';
				console.log(firstPoint, lastPoint)
				// if (currentRow.sparseLoc) {
				state.startPoint = new window.BMap.Point(
					firstPoint[0],
					firstPoint[1],
				);
				if (state.map.getZoom() < 16) {
					state.map.setZoom(16);
				}
				state.map.panTo(state.startPoint);
				// }
				// if (currentRow.terminus) {
				state.endPoint = new window.BMap.Point(
					lastPoint[0],
					lastPoint[1],
				);
				console.log(state, 'state')
				if (state.startPoint && state.endPoint) {
					drawRoad();
				}


			};
			// 绘制道路
			const drawRoad = () => {
				state.polylineList.forEach((item) => {
					state.map.removeOverlay(item);
				});

				if (state.startPoint && state.endPoint) {
					state.polylineList = [];
					var driving = new window.BMap.RidingRoute(state.map, {
						renderOptions: {
							map: state.map,
							autoViewport: false
						},
						onSearchComplete(results) {
							// 绘制途径路线
							console.log('23432c');
							if (results) {
								var sy = new window.BMap.Symbol(
									BMap_Symbol_SHAPE_BACKWARD_OPEN_ARROW, {
										scale: 0.5, //图标缩放大小
										strokeColor: '#fff', //设置矢量图标的线填充颜色
										strokeWeight: '2', //设置线宽
									});
								var icons = new window.BMap.IconSequence(sy, '10', '30');
								var pts = results.getPlan(0).getRoute(0).getPath();
								console.log(state.currentRow, '指数')
								let strokeColor = '#93D2F3'; // 默认颜色为蓝色（拥堵颜色）

								if (state.currentRow.congestIndex < 1.5) {
									strokeColor = 'rgba(117, 197, 31, 1)'; // 小于 1.5 时为绿色
								} else if (state.currentRow.congestIndex >= 1.5 && state.currentRow
									.congestIndex <= 2) {
									strokeColor = 'rgba(248, 162, 46, 1)'; // 1.5 到 2 之间为黄色
								} else if (state.currentRow.congestIndex > 2 && state.currentRow
									.congestIndex <= 4) {
									strokeColor = 'rgba(244, 59, 29, 1)'; // 大于 2 时为红色
								} else {
									strokeColor = 'rgba(170, 32, 23, 1)'; // 大于 4 时为深红色
								}

								var polyline = new window.BMap.Polyline(pts, {
									icons: [icons],
									strokeWeight: '8',
									strokeOpacity: 0.5,
									strokeColor: strokeColor, // 使用动态的颜色
								});
								// polyline.setStrokeColor('#59FF59');
								// polyline.setStrokeOpacity(1);
								state.polylineList.push(polyline);
								state.map.addOverlay(polyline);
							}
						},
						onMarkersSet(routes) {
							// console.log('---', routes);
							routes.forEach((item, index) => {
								state.map.removeOverlay(item);
							});
						},
						onInfoHtmlSet() {},
						onPolylinesSet(routes) {
							console.log("routesroutes", routes);
							// 路线绘制
							routes.forEach((Route) => {
								var polyline = Route.getPolyline();
								polyline.setStrokeColor('#CB2D56');
								// polyline.setStrokeOpacity(1)
								polyline.setStrokeWeight(1);
							});
						},
					});

					//途经点方式化路线:
					// driving.search(state.startPoint, state.endPoint, { waypoints: state.viaPoint });

					//分段画路线:
					if (state.viaPoint && state.viaPoint.length) {
						for (let i = 0; i < state.viaPoint.length; i++) {
							if (i === 0) {
								driving.search(state.startPoint, state.viaPoint[i]);
							} else {
								driving.search(state.viaPoint[i - 1], state.viaPoint[i]);
							}
						}
						driving.search(state.viaPoint[state.viaPoint.length - 1], state.endPoint);
					} else {
						driving.search(state.startPoint, state.endPoint);
					}
				}
			};
			onMounted(() => {
				state.time = [getToday(-1), getToday()];
				searchData();
			});
			return {
				searchData,
				mouseEnter,
				resetForm,
				clickItemTr,
				...toRefs(state),
			};
		},
	});
</script>

<style scoped lang="less">
	.congestion-content {
		// position: absolute;
		// z-index: 3;
		// top: 4%;
		// right: 0;
		width: 100%;
		height: 100%;
		background-color: 0;
		margin-top: 20px;

		.title {
			width: 100%;
			height: 50px;
			padding-top: 11px;
			padding-left: 5px;
			font-size: 20px;
			font-family: YouSheBiaoTiHei;
			color: #fff;
			line-height: 18px;
		}

		.tag-group {
			display: flex;
			color: rgba(255, 255, 255, 0.7);
			align-items: center;
			margin: 0 0 1vw;

			.tag-label {
				padding-right: 1vw;
			}

			.tag-cell {
				display: flex;
			}

			.tag-item {
				padding: 4px 10px;
				cursor: pointer;
				margin-right: 0.5vw;

				&:last-child {
					margin-right: 0;
				}
			}

			.tag-item.active {
				color: white;
				background: #037bff;
				border-radius: 4px;
			}

			.today {
				display: flex;
				justify-content: space-between;
				flex-grow: 1;

				.date-box {
					color: white;
				}

				.refresh {
					cursor: pointer;
					color: #4979ff;
				}
			}

			.date {
				border: 1px solid rgba(3, 123, 255, 1);
				border-radius: 4px;
				flex: 1;
			}
		}
	}

	// .table {
	// margin: 1.5625vw 0;
	// width: 100%;
	:deep(.el-table) {
		margin-top: 1.2vw;

		thead tr {
			background: linear-gradient(-90deg, #037bff 0%, #3996fc 100%) !important;
			box-shadow: 0px 4px 0px 0px rgba(77, 150, 236, 0.4);
			border-radius: 8px 0px 8px 0px;
		}

		.el-table__inner-wrapper::before {
			display: none;
		}

		.el-table__cell {
			padding: 15px 0;
		}

		.el-table__body tr.current-row {
			border: 1px solid #047cff !important;
			border-radius: 8px;
		}

		.el-table__body tr.current-row>td.el-table__cell {
			background: rgba(77, 150, 236, 0.4);
		}
	}

	:deep(.el-popper.is-light) {
		background-color: rgba(255, 255, 255, 0.7) !important;
		border: 1px solid #fff !important;
	}

	:deep(.el-table__body) {
		.index-color {
			width: 20px;
			height: 20px;
			line-height: 20px;
			text-align: center;
			border-radius: 50%;
		}

		.congestion-num {
			color: rgba(117, 197, 31, 1);
		}

		.congestion-num.orange {
			color: rgba(248, 162, 46, 1);
		}

		.congestion-num.red {
			color: rgba(244, 59, 29, 1);
		}

		& tr:nth-child(1) {
			& td:first-child {
				.index-color {
					background: #fb6036;
					color: white;
				}
			}
		}

		& tr:nth-child(2) {
			& td:first-child {
				.index-color {
					background: rgba(151, 203, 243, 1);
					color: white;
				}
			}
		}

		& tr:nth-child(3) {
			& td:first-child {
				.index-color {
					background: rgba(177, 102, 53, 1);
					color: white;
				}
			}
		}
	}

	// }
</style>